$(document).ready(function () {
	function showError(str,delay){	
		  if(delay){
			  $('#alertMessage').removeClass('success info warning').addClass('error').html(str).stop(true,true).show().animate({ opacity: 1,right: '10'}, 500,function(){
					  $(this).delay(delay).animate({ opacity: 0,right: '-20'}, 500,function(){ $(this).hide(); });																														   																											
				});
			  return false;
		  }
			  	$('#alertMessage').addClass('error').html(str).stop(true,true).show().animate({ opacity: 1,right: '10'}, 500);	
	  }
	  function showSuccess(str,delay){
		  if(delay){
			  $('#alertMessage').removeClass('error info warning').addClass('success').html(str).stop(true,true).show().animate({ opacity: 1,right: '10'}, 500,function(){
					  $(this).delay(delay).animate({ opacity: 0,right: '-20'}, 500,function(){ $(this).hide(); });																														   																											
				});
			  return false;
		  }
			  $('#alertMessage').addClass('success').html(str).stop(true,true).show().animate({ opacity: 1,right: '10'}, 500);	
	  }
	var list_id = '';
	$(function() {
		var timer;
		$(".search_cus").keyup(function(){
			clearTimeout(timer);
			var ms = 500;
			var q = $(this).val();
			if (q.length >= 2)
			{
				var dataString = "q=" + q ;
				$("#result_cus").html("<img src='../img/loadder/loader_green.gif'/>");
				timer = setTimeout(function() {
			    $.ajax({
			        type: "GET",
			        url: "search_cus",
			        data: dataString,
			        dataType: 'html',
			        success: function (data) {
			            $("#result_cus").html(data).hide().fadeIn();
			        }
			    })},ms)
			}
		})
	})
	
	
	$(function() {
		var timer;
		$(".search_product").keyup(function(){
			clearTimeout(timer);
			var ms = 500;
			var q = $(this).val();
			if (q.length >= 2)
			{
				var dataString = "q=" + q ;
				$("#result_product").html("<img src='../img/loadder/loader_green.gif'/>");
				timer = setTimeout(function() {
			    $.ajax({
			        type: "GET",
			        url: "search_product",
			        data: dataString,
			        dataType: 'html',
			        success: function (data) {
			            $("#result_product").html(data).hide().fadeIn();
			        }
			    })},ms)
			}
		})
	})
	
	
	$(".choose_cus").live("change", function(){
		$('#search_cus').validationEngine('hide');
		var id = $(this).val().substr(0,$(this).val().length - 4);
		var dataString = "id=" + id ;
		$("#result_choose_cus").html("<img src='../img/loadder/loader_green.gif'/>");
		$.ajax({
	        type: "GET",
	        url: "choose_cus",
	        data: dataString,
	        dataType: 'html',
	        success: function (data) {
	            $("#result_choose_cus").html(data).hide().fadeIn();
	        }
	    })
	})
	
	
	$(".choose_product").live("change", function(){
		$('#search_product').validationEngine('hide');
		var id = $(this).val().substr(0,$(this).val().length - 8);
		n = list_id.indexOf(id);
		if (n == -1) {
			var dataString = "id=" + id ;
			$("#result_choose_product").html("<img src='../img/loadder/loader_green.gif'/>");
			$.ajax({
		        type: "GET",
		        url: "choose_product_wholesale",
		        data: dataString,
		        dataType: 'html',
		        success: function (data) {
					list_id = list_id + id + ',';
		            $("#result_choose_product").html(data).hide().fadeIn();
		            $("#result_choose_product").attr('id',id+'_product');
		            $("#list_product").append("<div id='result_choose_product'></div>");
		             
		            $('.numericonly input').autotab_magic().autotab_filter('numeric');
		            $('form#validation').validationEngine();
		            $('#list_product #'+id+'_product select').selectmenu({
						 style: 'dropdown',	
					});
		        }
		    })
		    $('form#validation').validationEngine(); 
            $('.numericonly input').autotab_magic().autotab_filter('numeric');
		}
		else
		{
			showError("Đã thêm sản phẩm này",1000)
		}
		
	})
	
	
	$(".remove_product").live("click", function(){
		var id = $(this).attr('id').substr(0,$(this).attr('id').length-7);
		$("#" + id + "_product").validationEngine('hideAll');
		list_id = list_id.replace(id + ',','');
		showSuccess('Đã xóa sản phẩm',1000);
		$("#" + id + "_product").remove();
	})
	
	
	$("#create_wholesale_invoice").live("click", function(){
		var list_promotion = '';
		var list_quantity = '';
		var list_price = '';
		var cus = $(".cus_id").attr("id");
		if (cus == null)
		{
			$('#search_cus').validationEngine('showPrompt', 'Chọn khách hàng hoặc thêm khách hàng mới!', 'pass');
			showError('Chọn khách hàng hoặc thêm khách hàng mới!',1000);
			}
		else
			{
			if (list_id == '')
				{
				$('#search_product').validationEngine('showPrompt', 'Chọn sản phẩm', 'pass','topLeft');
				showError('Chọn sản phẩm hoặc thêm mới sản phẩm!',1000);
				$('#search_cus').validationEngine('hide');
				}
			else
				{
					$('#search_cus').validationEngine('hide');
					$('#search_product').validationEngine('hide');
					if($("#list_product").validationEngine('validate'))
					{
						var list_id_temp = list_id.substr(0,list_id.length-1);
						var array_id = list_id_temp.split(',');
						for (var i=0; i < array_id.length; i++)
						{
							id = array_id[i];
							list_promotion = list_promotion + $("#" + id + "_promotion").val() + ',';
							list_quantity = list_quantity + $("#" + id + '_quantity').val() + ',';
							list_price = list_price + $("#" + id + '_price').val() + ',';
						}
						var dataString = "list_id=" + list_id + "&cus=" + cus + "&list_quantity=" + list_quantity + "&list_promotion=" + list_promotion + "&list_price=" + list_price;
						$.ajax({
					        type: "GET",
					        url: "create_wholesale_invoice",
					        data: dataString,
					        dataType: 'html',
					        success: function (data) {
					        	showSuccess('Tạo hóa đơn thành công',1000);
					        }
					    })
					}
					else
						{
							$("#list_product").validationEngine('validate')
						}
				}
			}		
	})
	
	$('.new_cus').live("click", function() {
		if($(".newCus").validationEngine('validate'))
		{
			var name = $("#cus_name").val();
			var store = $("#cus_store").val();
			var address = $("#cus_address").val();
			var mobile = $("#cus_mobile").val();
			var phone = $("#cus_phone").val();
			var dataString = "name=" + name + "&store=" + store + "&address=" + address + "&phone=" + phone + "&mobile=" + mobile ;
			$("#result_choose_cus").html("<img src='../img/loadder/loader_green.gif'/>");
			$.ajax({
		        type: "GET",
		        url: "new_cus",
		        data: dataString,
		        dataType: 'html',
		        success: function (data) {
		        	showSuccess('Đã thêm khách hàng mới',1000);
	        		$(".newCus").fadeOut();
		        	var dataString2 = "id=" + data ;
					$.ajax({
				        type: "GET",
				        url: "choose_cus",
				        data: dataString2,
				        dataType: 'html',
				        success: function (data) {
				            $("#result_choose_cus").html(data).hide().fadeIn();
				        }
					})
		        }
		    })
		}
		else
		{
			$(".newCus").validationEngine('validate')
		}
	})
	
	
	$(".onChange").live("keyup",function() {
		var id = "" 
		if ($(this).attr("id").substr($(this).attr("id").length - 2, $(this).attr("id").length)== "ty" )
		{
			id = $(this).attr('id').substr(0,$(this).attr('id').length-9); 
		}
		else
		{
			id = $(this).attr('id').substr(0,$(this).attr('id').length-6);
		}
		if ($("#" + id + "_quantity") != "" && $("#" + id + "_cost") != "")
		{
			var sum = ""
			sum = $("#" + id + "_quantity").val() * $("#" + id + "_price").val(); 
			$("#" + id + "_sum").val(sum)
		}
		var list_id_temp = list_id.substr(0,list_id.length-1);
		var array_id = list_id_temp.split(',');
		var total = parseInt(0,10);
		for (var i=0; i < array_id.length; i++)
		{
			id = array_id[i];
			total += parseInt($("#" + id + "_sum").val())
		}
		$("#sum_result").html(total)
	})
	
	
	$(".onChange").live("change",function() {
		var id = "" 
		if ($(this).attr("id").substr($(this).attr("id").length - 2, $(this).attr("id").length)== "ty" )
		{
			id = $(this).attr('id').substr(0,$(this).attr('id').length-9); 
		}
		else
		{
			id = $(this).attr('id').substr(0,$(this).attr('id').length-6);
		}
		if ($("#" + id + "_quantity") != "" && $("#" + id + "_cost") != "")
		{
			var sum = ""
			sum = $("#" + id + "_quantity").val() * $("#" + id + "_price").val(); 
			$("#" + id + "_sum").val(sum)
		}
		var list_id_temp = list_id.substr(0,list_id.length-1);
		var array_id = list_id_temp.split(',');
		var total = parseInt(0,10);
		for (var i=0; i < array_id.length; i++)
		{
			id = array_id[i];
			total += parseInt($("#" + id + "_sum").val())
		}
		$("#sum_result").html(total)
	})
})